package org.exaple.laixe;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class ResultAnswersReview extends Activity{
	
	private ArrayList<Integer> Questions = new ArrayList<Integer>();// Store 30 questions
	private ArrayList<Integer> Answers = new ArrayList<Integer>();// store 30 answers
	private ArrayList<Integer> Corrects = new ArrayList<Integer>();// store 30 correct answer(1-4)
	private Long time;
	
	private RadioGroup rdAnswer;
	private RadioButton rd_1;
	private RadioButton rd_2;
	private RadioButton rd_3;
	private RadioButton rd_4;
	private WebView webView_thi;	
	private Button btn_thiNext;
	private Button btn_thiBack;	
	private String currentQuestion; 	// Current Question(1-405)
	private int currentNumberofAnswers;	// Current number of Answers(1/2/3/4) of current Question
	private int indexof30 = 0;			// current Index of Question(0-29)
	
	private TextView QuestionNavigation;	// Text control to display current question /30
	private LinearLayout Container30Questions;
	private TextView timeRemaining;
	
	private int scale; 	// store scale for webview  in next questions
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thi);
        
        // get Extra information from Result(Thi) class
        Bundle b = getIntent().getExtras();
        Questions = b.getIntegerArrayList("Questions");
        Answers = b.getIntegerArrayList("Answers");
        Corrects = b.getIntegerArrayList("Corrects");
        time = b.getLong("time");
        
        
        if(savedInstanceState != null) {
        	// restoreInstanseState
        }
        else {        	
        	indexof30 = 0;
        }
        //
        currentQuestion = Questions.get(indexof30).toString();
        System.out.println(Questions.toString());
        //       
        rdAnswer = (RadioGroup) findViewById(R.id.exam_radio_group);
        rd_1 = (RadioButton) findViewById(R.id.exam_radio_1);
        rd_2 = (RadioButton) findViewById(R.id.exam_radio_2);
        rd_3 = (RadioButton) findViewById(R.id.exam_radio_3);
        rd_4 = (RadioButton) findViewById(R.id.exam_radio_4);
        webView_thi = (WebView) findViewById(R.id.webView_thi);
        btn_thiNext = (Button) findViewById(R.id.exam_Next_button);
        btn_thiBack = (Button) findViewById(R.id.exam_Back_button);
        //
        QuestionNavigation = (TextView) findViewById(R.id.ExamTitleBar_QuestionInfo);
        Container30Questions = (LinearLayout) findViewById(R.id.ExamTitleBar_30QuestionsContainer);
        timeRemaining = (TextView) findViewById(R.id.ExamTitleBar_TimeRemaining);
        
        timeRemaining.setText(time.toString());
        
        // Display 30 questions = 30 buttons
        add30QuestionButtons();
        // update State 30 Questions;
        update30QuestionButtonState();
        
        Container30Questions.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {				
				Toast.makeText(getBaseContext(), "Clicked 30 ?", Toast.LENGTH_SHORT).show();
			}
		});
        
        
        // Set zoom control       
        webView_thi.getSettings().setSupportZoom(true);//Zoom Control on web (You don't need this 
        											//if ROM supports Multi-Touch
        webView_thi.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
        webView_thi.getSettings().setUseWideViewPort(true);  
        webView_thi.getSettings().setJavaScriptEnabled( true );
        // Show Question number 1
        ProcessQuestionString();
        ShowQuestion( String.valueOf(currentQuestion) );
        
        System.out.println(Questions.toString());
        
        // handle to process button Back
        btn_thiBack.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {				
				if(indexof30 > 0) {
					indexof30 -- ;
					currentQuestion = Questions.get(indexof30).toString(); 
					ProcessQuestionString();
					ShowQuestion( String.valueOf(currentQuestion) );
					
				}
			}
		});
        // handle to process button Next
        btn_thiNext.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {
				if( indexof30 < 29) {
					indexof30 ++ ;
					currentQuestion = Questions.get(indexof30).toString();
					ProcessQuestionString();
					ShowQuestion( String.valueOf(currentQuestion) );
					
				}
			}
		}); 
	}
	// Create Option Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.result_review, menu);
		return true;
	}
		
	// Process When user click on Option menu
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.resultReview_menuThietLap:
			startActivity(new Intent(this, Prefs.class));
			return true;		
		case R.id.resultReview_menuThoat:
			onExit();
			return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
	// Event Back button when users press
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {System.out.println(currentQuestion);
	        if(indexof30 == 0 ) {
	        	// asking user to exit if they are viewing the first question
	        	System.out.println(indexof30);
	        	onExit();
	        } else {
	        	previous();
	        }
        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		savedInstanceState.putInt( "currentQuestionIndex", indexof30);		// Store Current Question Index
	}
	
	@Override 
	public void onRestoreInstanceState(Bundle state) {
		indexof30 = state.getInt("currentQuestionIndex");	
		// show current Question watching
		ProcessQuestionString();
        ShowQuestion( String.valueOf(currentQuestion) );
		super.onRestoreInstanceState(state);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		Music.play(this, "file:///sdcard/data/org.exaple.laixe/tambietchimen.mp3");
	}
	
	@Override
	public void onPause() {
		super.onPause();
		Music.stop(this);
	}
	
	private void onExit() {		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.resultReview_ThoatMessage)
		       .setCancelable(false)
		       .setTitle(R.string.resultReview_ThoatTitle)
		       .setPositiveButton(R.string.resultReview_ThoatbtnYes, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {		        	   	
		                finish();
		           }
		       })
		       .setNegativeButton(R.string.resultReview_ThoatbtnNo, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       })
		       .setIcon(R.drawable.ic_dialog_info);
		AlertDialog alert = builder.create();		
		alert.show();
	}
	
	private void previous() {
		if(indexof30 > 0) {
			indexof30 -- ;
			currentQuestion = Questions.get(indexof30).toString(); 
			ProcessQuestionString();
			ShowQuestion( String.valueOf(currentQuestion) );
			
		}
	}
	// Process string "Question" 
	public void ProcessQuestionString() {
		int currentQues = Integer.parseInt(currentQuestion);		
		String current = "";
		if( currentQues <= 0 )
			currentQues = 1;
		if( currentQues >= 405)
			currentQues = 405;
		
		if( currentQues >= 1 && currentQues <= 9)
			current = "0" + "0" + String.valueOf( currentQues );
		else if( currentQues >=10 && currentQues <=99 )
			current  = "0" + String.valueOf( currentQues );
		else 
			current = String.valueOf( currentQues );
		
		currentQuestion = current;
	}
	
	// Show questions in webView
	public void ShowQuestion(String number) {
    	String baseUrl = "file:///sdcard/data/org.exaple.laixe/";
    	String data = getStringFromURL( number + ".html");    	
    	// Display current question
    	scale = (int)(100 * webView_thi.getScale()); // keep the last zoom ratio
    	webView_thi.loadDataWithBaseURL(baseUrl, data, "text/html", "utf-8", "");
    	webView_thi.setInitialScale(scale);
    	//show Answer
    	currentNumberofAnswers = data.split("</li><li class=").length;
    	// Show current question in titleBar
    	QuestionNavigation.setText( String.valueOf(indexof30 + 1) + "/30");
    	// 
    	DoAfterChangingQuestion();
    	//
    	System.out.println(Answers.get(indexof30));
    	System.out.println(Answers.toString());
    }
    
    // Read File from Assets and return to a string to process later
    public String getStringFromURL(String s) {
    	String str = "";
    	try {
	    	InputStream is = getApplicationContext().getAssets().open(s);
	    	InputStreamReader input = new InputStreamReader(is);
	    	int charRead;	    	
	    	char[] bufer = new char[2000];
	    	while( (charRead = input.read(bufer)) > 0 ) {
	    		String readString = String.copyValueOf(bufer, 0, charRead);
	    		str += readString;
	    		bufer = new char[2000];
	    	}
	    	is.close();
    	}
    	catch(IOException io) {
    		io.printStackTrace();
    	}    	
    	// Process str when displaying anwser
    	// Đổi style:"display= none" -> true
    	str = str.replaceAll( "display: none", "display: true");    	
    	
    	return str;
    	
    }
    public void SetVisibilityforRadio() {
    	// Invi 4 radio buttons
    	for (int i = 0; i < 4; i++) {
			rdAnswer.getChildAt(i).setVisibility(View.INVISIBLE);
		}
    	
    	// Show radio button user checked (right/wrong) and not show radio not check
    	// user don't check any buttons
    	if(Answers.get(indexof30) == 0)
    		return;
    	// user checked correctly
    	else if(Answers.get(indexof30) == Corrects.get(indexof30)){
    		 RadioButton button = (RadioButton)rdAnswer.getChildAt(Answers.get(indexof30) -1);
             button.setVisibility(View.VISIBLE);
             button.setBackgroundDrawable(null);
             button.setButtonDrawable(null);
             button.setButtonDrawable(R.drawable.radio_button_1_selected);
             button.setButtonDrawable(R.drawable.radio_button_2_selected);
             button.setButtonDrawable(R.drawable.radio_button_3_selected);
             button.setButtonDrawable(R.drawable.radio_button_4_selected);
    	}
    	else
    	{
    		 RadioButton button = (RadioButton)rdAnswer.getChildAt(Answers.get(indexof30) -1);
             button.setVisibility(View.VISIBLE);
             button.setBackgroundDrawable(null);
             button.setButtonDrawable(null);
             button.setButtonDrawable(R.drawable.radio_button_1_incorrect);
             button.setButtonDrawable(R.drawable.radio_button_2_incorrect);
             button.setButtonDrawable(R.drawable.radio_button_3_incorrect);
             button.setButtonDrawable(R.drawable.radio_button_4_incorrect);
    	}
    		
    }
    
    
    
    // Set ...
    public void DoAfterChangingQuestion() {
    	
    	// process RadioGroup Answer(check and invi)    	
    	SetVisibilityforRadio();    	  	
    	rdAnswer.clearCheck();    	
    }
    
    public void update30QuestionButtonState() {
    	for (int i = 0; i < 30; i++) {
			if(Answers.get(i) == 0)
				update1QuestionButtonState(i, QuestionState.UNANSWERED);
			else if(Answers.get(i) != Corrects.get(i))
				update1QuestionButtonState(i, QuestionState.INCORRECT);
			else if(Answers.get(i) == Corrects.get(i))
				update1QuestionButtonState(i, QuestionState.CORRECT);				
		}
    }

	/**
	 * Update state for a question button in navigation section
	 * @param button Question button to update UI
	 * @param state New state for questions
	 */
	private void update1QuestionButtonState(Button button, QuestionState state) {
		 if(state == QuestionState.ANSWERED) {
             button.setBackgroundResource(R.color.titleBar_answered_question);
	     } else if(state == QuestionState.UNANSWERED) {
	             button.setBackgroundResource(R.color.titleBar_unanswered_question);
	     } else if(state == QuestionState.CORRECT) {
	             button.setBackgroundResource(R.color.titleBar_correct_question);
	     } else if(state == QuestionState.INCORRECT) {
	             button.setBackgroundResource(R.color.titleBar_incorrect_question);
	     }	
	}

	/**
	 * Update state for a question, looking by question index, which starts from zero
	 * @param questionIndex Index of question to update state, which starts from zero
	 * @param state New state for questions
	 */
	private void update1QuestionButtonState(int questionIndex, QuestionState state) {
	    int lineNumber = (questionIndex / 10) + 1;
	    int buttonIndex = questionIndex % 10;
	    
	    LinearLayout line;
	    switch (lineNumber) {
	    case 1:
	            line = (LinearLayout)findViewById(R.id.ExamTitleBar_10Questions_Row1);
	            break;
	    case 2:
	            line = (LinearLayout)findViewById(R.id.ExamTitleBar_10Questions_Row2);
	            break;
	    default:
	            line = (LinearLayout)findViewById(R.id.ExamTitleBar_10Questions_Row3);
	            break;
	    }
	    update1QuestionButtonState((Button)line.getChildAt(buttonIndex), state);
	    
	    //quickActionMenu.updateQuestionState(questionIndex, state);
}




	/**
	 * Add 30 question navigation buttons to the status bar on top
	 */
	private void add30QuestionButtons() {
	        LinearLayout container = (LinearLayout)findViewById(R.id.ExamTitleBar_30QuestionsContainer);
	        int count = container.getChildCount();	// =3(0,1,2) (trong LinearLayout TitleBar_30QuestionsContainer chứa 3 cái container con )
	        for(int x = 0; x < count; x++) {
	                add10QuestionButtonsForALine((LinearLayout)container.getChildAt(x), x);	//(0,1,2)
	        }
	}
	
	/**
	 * Add 10 questions navigation buttons to a line, which is a LinearLayout
	 * @param line A buttons container to add button to
	 * @param lineIndex Index of line
	 */
	private void add10QuestionButtonsForALine(LinearLayout line, int lineIndex) {
        Button button;
        int start = lineIndex * 10;
        int end = start + 10;
        for(int x = start; x < end; x++) {
                final int index = x;
                //System.out.println("dsfdsfdsfdsfdsfdsfdsfds");
                // create a button from template
                button = (Button)getLayoutInflater().inflate(R.layout.button_titlebar, line, false);
                // add that button to the linearlayout
                button.setId(x);
                line.addView(button);
                // Add click event for this button, to show quick action menu / question chosen
                button.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                        	
                        	// Display Action menu to choose 30 Questions
                                //context.vibrateIfEnabled();
                                //quickActionMenu.show();
                                //quickActionMenu.setSelectedQuestion(currentQuestionIndex);
                        	
                        	// Display  Question chosen right now
                        	for (int i = 0; i < 30; i++) {
								if(i == v.getId() )  {
									indexof30 = i ;
									currentQuestion = Questions.get(indexof30).toString(); 
									ProcessQuestionString();
									ShowQuestion( String.valueOf(currentQuestion) );
									
								}
									
							}
                        	
                        }
                });                
        }
	}
}
